# -*- coding: utf-8 -*-
# @Time    : 2019/10/2 12:24
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : time_line_contentType.py
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType

from django.db.models.signals import post_save

"""
ContentType的巧妙用法-Timeline设计
每当下面三个模块有新数据创建时，都会在Index模型类中创建一条数据；
在Index模型类中将数据进行按时间进行倒序排列，
首页展示数据都通过Index取到另外三个模块的数据
8-19中讲解
"""


class Index(models.Model):
    """首页"""
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey("content_type", "object_id")

    pub_date = models.DateTimeField()  # 发表时间

    class Meta:
        ordering = ["-pub_date"]

    @property
    def content(self):
        return self.content_object.content

# indexs.content  # 获取新闻的content字段

# self.content_object.content  获取


class News(models.Model):
    """动态"""
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
    # index = GenericRelation(Index)

    # def save(self, force_insert=False, force_update=False, using=None,
    #          update_fields=None):
    #     ct = ContentType.objects.get_for_model(self)
    #     # object_id News表中的主键id content_type_id哪一个app下的哪一个模型类
    #     Index.objects.get_or_create(content_type_id=ct, object_id=self.id, pub_date=self.pub_date)


class Article(models.Model):
    """文章"""
    title = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
    # index = GenericRelation(Index)

    # def save(self, force_insert=False, force_update=False, using=None,
    #          update_fields=None):
    #     ct = ContentType.objects.get_for_model(self)
    #     # object_id News表中的主键id content_type_id哪一个app下的哪一个模型类
    #     Index.objects.get_or_create(content_type_id=ct, object_id=self.id, pub_date=self.pub_date)


class Question(models.Model):
    """问题"""
    title = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
    # index = GenericRelation(Index)

    # def save(self, force_insert=False, force_update=False, using=None,
    #          update_fields=None):
    #     ct = ContentType.objects.get_for_model(self)
    #     # object_id News表中的主键id content_type_id哪一个app下的哪一个模型类
    #     Index.objects.get_or_create(content_type_id=ct, object_id=self.id, pub_date=self.pub_date)


def create_index(sender, instance, **kwargs):
    """信号量函数"""
    if "created" in kwargs:  # 每次创建的时候触发
        ct = ContentType.objects.get_for_model(instance)
        # object_id News表中的主键id content_type_id哪一个app下的哪一个模型类
        Index.objects.get_or_create(content_type_id=ct, object_id=instance.id, pub_date=instance.pub_date)


post_save.connect(create_index, sender=News)
post_save.connect(create_index, sender=Article)
post_save.connect(create_index, sender=Question)

